# -*- coding: utf-8 -*-

#from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.urls import reverse
from . import config

from TestModel.models import User, Contact

@login_required
def signin(request):
    """ 登陆 """
    request.encoding='utf-8'
    args = request.GET if request.method == 'GET' else  request.POST
    print ('### request.method:%s'% request.method)
    if request.method == 'GET':
        args = request.GET
        mobile   = args.get('mobile', '').strip('')
        password = args.get('password', '').strip('')

        if mobile and password:
            # 修改密码成功，直接登录
            return login_check(request, mobile, password)
        return render(request, 'signin.html')

    ctx ={}
    mobile      = args.get('mobile', '').strip()
    password    = args.get('password', '').strip()
    code        = args.get('code', '').strip()
    code        = u'%s'% code
    ctx['rlt']  = mobile
    if mobile and password and code:
        return login_check(request, mobile, password, args, code)

    log_info('### mobile:%s, password:%s, code:%s'%(mobile, password, code))
    return render(request, 'signin.html', ctx)


@login_required
def login_check(request, mobile='', password='', form={}, code='', errmsg=None):
    """ 登陆检查 """

    session = request.session
    if not mobile:
        return render(request, 'signin.html', {'f':form, 'errmsg':u'手机号不能为空'})

    if not password:
        return render(request, 'signin.html', {'f':form, 'errmsg':u'密码不能为空'})

    if len(code) != 6:
        return render(request, 'signin.html', {'f':form, 'errmsg':u'输入6位验证码'})

    code_text = session.get('code_text', '')
    print("### config['DATABASES']:%s"% config.DATABASES)
    if code_text.upper() != code.upper() and config.DATABASES['default']['HOST'] != 'localhost':
        return render('signin.html',
                    {'f':{'mobile':mobile},
                    'errmsg':u'输入的验证码不正确, 请重新获取'})

    me = Contact.objects.filter(id=1)
    print('cccccccccccccccccccccccc:%s'% me.email)
    if me is None:
        return render('signin.html', {'f':form, 'errmsg':u'用户不存在'})

    up = UserPassword.query.filter(UserPassword.uid == me.uid).\
            filter(UserPassword.type == 1).first()
    if up is None:
        return render('signin.html', {'f':form, 'errmsg':u'还没有设置密码'})

    sha256_password = sha256(password).hexdigest()
    sha256_password = sha256(sha256_password+up.salt).hexdigest()
    if sha256_password != up.password:
        return render('signin.html', {'f':form, 'errmsg':u'密码错误'})

    ua = UserAdmin.query.filter(UserAdmin.uid == me.uid).\
            filter(UserAdmin.role_id > 0).first()

    if ua is None:
        return render('signin.html', {'f':form, 'errmsg':u'您没有权限登录系统，请联系可爱的管理员'})

    role = Role.query.get(ua.role_id)
    if not role:
        return render('signin.html', {'f':form, 'errmsg':u'获取角色信息失败，请联系可爱的管理员'})

    role_id_list = user_role_id_list(me.uid)
    role_id_list.remove(ua.role_id)
    ROLE_NAME = role_name()

    session['admin_id']     = me.uid
    session['admin_name']   = me.mobile
    session['uid']          = me.uid
    session['mobile']       = mobile
    session['nickname']     = me.nickname
    session['cs_id']        = me.cs_id
    session['role_id']      = ua.role_id
    session['role_temp_list'] = get_role_list(role_id_list) if len(role_id_list) > 0 else []
    session['role_name']    = ROLE_NAME.get(ua.role_id, '')
    session['menu']         = menu(ua.role_id)

    if not session['menu'] and ua.role_id == 1:
        return redirect(url_for('sys.menu_list'))
    else:
        return redirect(reverse('django_python3.views.signin', args=[]))
